import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'
import { useAuthStore } from '@/stores/useAuthStore'

// 路由组件懒加载
const Layout = () => import('@/layout/AppLayout.vue')
const HomePage = () => import('@/views/home/HomePage.vue')
const Register = () => import('@/views/auth/Register.vue')
const ProductDetail = () => import('@/views/product/ProductDetail.vue')
const Login = () => import('@/views/auth/Login.vue')
const UserProfile = () => import('@/views/user/Profile.vue')
const FavoritesPage = () => import('@/views/user/FavoritesPage.vue')
const ProductCategory = () => import('@/views/product/Category.vue')
const ProductList = () => import('@/views/product/ProductList.vue')

const SearchResults = () => import('@/views/product/SearchResults.vue')
const CartPage = () => import('@/views/cart/CartPage.vue')
const Checkout = () => import('@/views/checkout/Checkout.vue')
const OrderList = () => import('@/views/order/OrderList.vue')
const OrderDetail = () => import('@/views/order/OrderDetail.vue')
const OrderSuccess = () => import('@/views/order/OrderSuccess.vue')
const CommentPage = () => import('@/views/comments/CommentPage.vue')
const NotFound = () => import('@/views/error/NotFound.vue')
const ServerError = () => import('@/views/error/ServerError.vue')

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: Layout,
    children: [
      // 首页
      {
        path: '',
        name: 'Home',
        component: HomePage,
        meta: { title: '首页', keepAlive: true },
      },

      // 秒杀活动
      {
        path: 'flash-sale',
        name: 'FlashSale',
        component: () => import('@/components/product/FlashSale.vue'),
        meta: { title: '限时秒杀' },
      },
      // 品牌
      // {
      //   path: 'brand',
      //   name: 'Brand',
      //   component: BrandList,
      //   meta: { title: '品牌' },
      // },
      {
        path: 'product/:id',
        name: 'ProductDetail',
        component: ProductDetail,
        meta: { title: '商品详情' },
      },
      // 商品相关
      {
        path: 'category/:id',
        name: 'Category',
        component: ProductCategory,
        meta: { title: '分类商品' },
      },
      {
        path: 'products',
        name: 'ProductList',
        component: ProductList,
        meta: { title: '商品列表' },
      },
    ],
  },

  // 用户中心（一级路由，需要认证）
  {
    path: '/user/profile',
    name: 'UserProfile',
    component: UserProfile,
    meta: { requiresAuth: true, title: '个人资料', keepAlive: true },
  },

  {
    path: '/user/favorites',
    name: 'Favorites',
    component: FavoritesPage,
    meta: { requiresAuth: true, title: '我的收藏' },
  },

  // 购物车（一级路由，需要认证）
  {
    path: '/cart',
    name: 'Cart',
    component: CartPage,
    meta: { requiresAuth: true, title: '购物车' },
  },

  // 结算中心（一级路由，需要认证）
  {
    path: '/checkout',
    name: 'Checkout',
    component: Checkout,
    meta: { requiresAuth: true, title: '结算中心' },
  },
  {
    path: '/payment',
    name: 'Payment',
    component: () => import('@/views/checkout/Payment.vue'),
    meta: { requiresAuth: true, title: '订单支付' },
  },
  {
    path: '/payment/success',
    name: 'PaymentSuccess',
    component: () => import('@/views/checkout/PaymentSuccess.vue'),
    meta: { requiresAuth: true, title: '支付成功' },
  },

  // 订单管理（一级路由，需要认证）
  {
    path: '/orders',
    name: 'OrderList',
    component: OrderList,
    meta: { requiresAuth: true, title: '我的订单' },
  },
  {
    path: '/order/:id',
    name: 'OrderDetail',
    component: OrderDetail,
    meta: { requiresAuth: true, title: '订单详情' },
  },
  {
    path: '/order/success',
    name: 'OrderSuccess',
    component: OrderSuccess,
    meta: { requiresAuth: true, title: '下单成功' },
  },

  // 评论页面
  {
    path: '/comments/:goodsId',
    name: 'CommentPage',
    component: CommentPage,
    meta: { requiresAuth: true, title: '商品评价' },
  },

  // 认证页面（独立于主布局）
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', guestOnly: true },
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { title: '注册', guestOnly: true },
  },

  // 错误页面
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: { title: '页面不存在' },
  },
  {
    path: '/500',
    name: 'ServerError',
    component: ServerError,
    meta: { title: '服务器错误' },
  },

  // 匹配未定义路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 优先使用浏览器保存的位置
    if (savedPosition) {
      return savedPosition
    }

    // 对于返回首页的情况，特别处理
    if (to.name === 'Home' && from.name === 'ProductDetail') {
      // 不干预首页的滚动位置，由首页组件自己处理
      return false
    }

    // 进入详情页时滚动到顶部
    if (to.name === 'ProductDetail') {
      return { top: 0, behavior: 'smooth' }
    }

    // 其他情况保持当前位置
    return false
  },
})
// 路由守卫 - 认证检查
router.beforeEach(async (to, from, next) => {
  console.log(`[Router] Navigating from ${from.fullPath} to ${to.fullPath}`)

  // 在路由守卫中创建 store 实例
  const authStore = useAuthStore()
  // 确保认证状态已经初始化 - 使用正确的 Pinia 方法
  const isAuthenticated = authStore.isAuthenticated()

  // 检查认证要求
  if (to.meta.requiresAuth) {
    if (!isAuthenticated) {
      console.log('[Auth Guard] Redirecting to login for protected route')
      return next({
        path: '/login',
        query: { redirect: to.fullPath },
      })
    }

    // 额外检查token和用户信息有效性
    if (!authStore.token || !authStore.user) {
      console.log('[Auth Guard] Token or user info not found, forcing logout')
      // 直接清理本地状态，不调用后端接口
      authStore.clearAuth()
      return next({
        path: '/login',
        query: { redirect: to.fullPath, reason: 'session_expired' },
      })
    }
  }

  // 阻止已登录用户访问登录/注册页面
  if (to.meta.guestOnly && isAuthenticated) {
    console.log('[Auth Guard] User is authenticated, redirecting to home')
    return next({ path: '/' })
  }

  // 设置页面标题
  const titlePrefix = '电商平台'
  document.title = to.meta.title ? `${titlePrefix} - ${to.meta.title}` : titlePrefix

  next()
})

// 导出安装函数
export const setupRouter = (app: App<Element>) => {
  app.use(router)
}

export default router
